﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.Azure;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Common;
using ELearning.Common.Helpers;
using ELearning.Common.Http;
using ELearning.Models;
using ELearning.Models.ViewModel.WinnerNews;
using RestSharp;
using static Microsoft.Graph.CoreConstants;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 新增相关功能
    /// </summary>
    public class WinnerNewsController : BaseApiController
    {
        /// <summary>
        /// 新增操作service
        /// </summary>
        private ENewsService NewsService => new ENewsService();
        private EWinnerNewsService WinnerNewsService => new EWinnerNewsService();

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        [HttpPost, Route("api/winnerNews/GetNewsList")]
        public ServiceResponse<WinnerNewsViewModel> GetNewsList(WinnerNewsRequest request)
        {
            
            Expression<Func<EWinnerNews, bool>> whereLamdba = (u) => u.IsDelete == false;
            if (!string.IsNullOrEmpty(request.Name))
                whereLamdba = whereLamdba.And(w => w.Name.Contains(request.Name));
            if (!string.IsNullOrEmpty(request.StoreName))
                whereLamdba = whereLamdba.And(w => w.StoreName.Contains(request.StoreName));

            var viewModel = new WinnerNewsViewModel();
            var news = WinnerNewsService.FindPageList(request.Page, request.PageSize, out var total, request.OrderBy, request.SortDir, whereLamdba);
            if (news != null)
            {
                viewModel.TotalCount = total;
                foreach (var eWinnerNewse in news)
                {
                    int yearmax = 0, monthmax = 0;
                    yearmax = GetMax("Year",eWinnerNewse.YearName);
                    monthmax = GetMax("Month", eWinnerNewse.YearName);
                    var v = eWinnerNewse.MapTo<WinnerNewsItem, EWinnerNews>();
                    v.MonthPercentage = (v.MonthCount*100) / monthmax;
                    v.YearPercentage = (v.YearCount*100) / yearmax;
                    v.CreateTime = eWinnerNewse.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    v.ModifyTime = eWinnerNewse.ModifyTime.ToString("yyyy-MM-dd HH:mm:ss");
                    viewModel.NewsItems.Add(v);
                }
            }
            return ServiceResponse<WinnerNewsViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }


        /// <summary>
        /// 展示新闻详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("api/winnerNews/GetNewsByID")]
        public ServiceResponse<WinnerNewsItem> GetNewsByID(Guid id)
        {
            var news = WinnerNewsService.Find(w => w.ID == id);
            var v = news.MapTo<WinnerNewsItem, EWinnerNews>();
            return ServiceResponse<WinnerNewsItem>.SuccessResponse(CommonConst.OprateSuccessStr, v);
        }

        /// <summary>
        /// 根据课程id 获取相关课程列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("api/winnerNews/GetRelationNewsByID")]
        public ServiceResponse<List<EWinnerNews>> GetRelationNewsByID(Guid id)
        {
            List<EWinnerNews> newslist = new List<EWinnerNews>();
            var news = WinnerNewsService.Find(w => w.ID == id);
            if (news != null)
            {
                newslist = WinnerNewsService.FindList(w => w.ID!=news
                .ID&&w.MonthName==news.MonthName&&w.YearName==news.YearName ).OrderByDescending(w => w.CreateTime).Take(5).ToList();
            }
            return ServiceResponse<List<EWinnerNews>>.SuccessResponse(CommonConst.OprateSuccessStr, newslist);
        }

        /// <summary>
        /// 获取最大值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public int GetMax(string str,string yearname)
        {
            int max = 0;
            var news = WinnerNewsService.FindList(w=>w.IsDelete==false&&w.YearName==yearname);
            if (news != null)
            {
                if (str == "Year")
                {
                    max = news.Select(w => w.YearCount).Max();
                }
                else
                {
                    max = news.Select(w => w.MonthCount).Max();
                }
            }
            return max;
        }

        /// <summary>
        /// 添加新闻
        /// </summary>
        [HttpPost, Route("api/winnerNews/AddNews")]
        public object AddNews(WinnerNewsItem viewModel)
        {
            var m = WinnerNewsService.Find(w => w.Name == viewModel.Name && w.YearName == viewModel.YearName && w.MonthName == viewModel.MonthName);
            if (m != null)
                return ServiceResponse<bool>.SuccessResponse(CommonConst.WinnerNewsNotOprate, false);
            var model = viewModel.MapTo<EWinnerNews, WinnerNewsItem>();
            model.ID = GuidUtil.NewSequentialId();
            model.Creater = CurrentUserModel?.LoginName ?? string.Empty;
            model.CreateTime = DateTime.Now;
            model.ModifyTime = DateTime.Now;
            model.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
            WinnerNewsService.Add(model);

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 更新新闻
        /// </summary>
        [HttpPost, Route("api/winnerNews/UpdateNews")]
        public object UpdateNews(WinnerNewsItem viewModel)
        {
            var m = WinnerNewsService.Find(w => w.Name == viewModel.Name && w.YearName == viewModel.YearName && w.MonthName == viewModel.MonthName && w.ID != viewModel.ID);
            if (m != null)
                return ServiceResponse<bool>.SuccessResponse(CommonConst.WinnerNewsNotOprate, false);

            var model = WinnerNewsService.Find(w => w.ID == viewModel.ID);
            if (model != null)
            {
                model.ImageURL = viewModel.ImageURL;
                model.Name = viewModel.Name;
                model.Sort = viewModel.Sort;
                model.StoreName = viewModel.StoreName;
                model.YearName = viewModel.YearName;
                model.YearCount = viewModel.YearCount;
                model.MonthName = viewModel.MonthName;
                model.MonthCount = viewModel.MonthCount;
                model.TypeName = viewModel.TypeName;
                model.LableName = viewModel.LableName;
                model.CountSum = viewModel.CountSum;
                model.Mark = viewModel.Mark;

                model.ModifyTime = DateTime.Now;
                model.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
                WinnerNewsService.Update(model);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="id">新闻id</param>
        [HttpPost, Route("api/winnerNews/DeleteNews")]
        public object DeleteNews(Guid id)
        {
            var news = WinnerNewsService.Find(w => w.ID == id);
            if (news != null)
            {
                news.IsDelete = true;
                WinnerNewsService.Update(news);
            }
            return ServiceResponse<int>.SuccessResponse(CommonConst.OprateSuccessStr, 1);
        }

        /// <summary>
        /// 发布新闻
        /// </summary>
        [HttpPost, Route("api/winnerNews/PublishNews")]
        public object PublishNews(Guid id, int status)
        {
            var news = NewsService.GetNews(id);
            if (news != null)
            {
                news.States = status;
                if (status == 1)
                    news.ReleaseTime = DateTime.Now;
                NewsService.Update(news);
            }
            return ServiceResponse<int>.SuccessResponse(CommonConst.OprateSuccessStr, 1);
        }

        /// <summary>
        /// 置顶和取消置顶
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost, Route("api/winnerNews/TopModel")]
        public object TopModel(Guid id, int status)
        {
            var b = false;
            var news = NewsService.GetNews(id);
            if (news != null)
            {
                if (status == 1)
                {
                    news.IsStick = DateTime.Now;
                }
                else
                {
                    news.IsStick = news.CreateTime;
                }
                news.ReleaseTime = DateTime.Now;
                b = NewsService.Update(news);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, b);
        }

        /// <summary>
        /// 导入销冠风采
        /// </summary>
        [HttpPost, Route("api/winnerNews/ImportWinnerNews")]
        [AllowAnonymous]
        public object ImportWinnerNews()
        {
            var result = CommonConst.UploadFailDefaultUrl;
            var filelist = HttpContext.Current.Request.Files;
            var users = new List<EWinnerNews>();
            var path = HttpContext.Current.Server.MapPath("/ImportConfig/winnerNewsConfig.xml");
            var xr = XMLHelper.ReadToHashtable(path);
            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        if (ext == "xlsx")
                            dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream, xr.ImportHashtable); //excel转成datatable
                        else
                            dataTable = ExcelHelp.ExcelToTableForXLS(file.InputStream); //excel转成datatable
                    }
                    users = dataTable.ToDataList<EWinnerNews>(); //datatable转成list
                }
            }
            var succe = new List<EWinnerNews>();
            var faile = new List<EWinnerNews>();
            var exportList = new List<EWinnerNews>();
            var names = WinnerNewsService.FindList(u => !u.IsDelete).Select(u => new{ u.Name ,u.YearName,u.MonthName}).ToList();
            //数据list转成数据库实体对应的list
            foreach (var u in users)
            {
                u.ID = GuidUtil.NewSequentialId();
                u.CreateTime = DateTime.Now;
                u.ModifyTime = DateTime.Now;
                u.Creater = CurrentUserModel?.LoginName ?? string.Empty;
                u.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
                if (string.IsNullOrEmpty(u.Name) || string.IsNullOrEmpty(u.YearName) || string.IsNullOrEmpty(u.YearName)
                    || string.IsNullOrEmpty(u.StoreName) || string.IsNullOrEmpty(u.MonthName)
                    || string.IsNullOrEmpty(u.TypeName) || string.IsNullOrEmpty(u.LableName)
                    )
                {
                    u.LableName = "冠军姓名/年/月/所属门店/月销售/年累销售/分类/标签/数量/排序不能为空";
                    faile.Add(u);
                    exportList.Add(u);
                    continue;
                }

                var t = names.Where(f => f.Name == u.Name && f.YearName == u.MonthName && f.MonthName == u.MonthName );
                var p1 = succe.Where(f => f.Name == u.Name && f.YearName == u.MonthName && f.MonthName == u.MonthName);
                if (t.Any() || p1.Any())
                {
                    u.LableName = "冠军姓名/年/月重复";
                    exportList.Add(u);
                    faile.Add(u);
                }
                else
                {
                    succe.Add(u);
                }
            }
            var dt = succe.ToDataTable(null);
            dt.TableName = "EWinnerNews";
            var r = succe.Count;
            SqlBulkCopyHelper.SaveTable(dt);

            var extDt = exportList.ToDataTable(xr.ExportHashtable);
            var fileFullPath = GetPath();
            ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
            var url = SaveFile("销冠风采失败信息.xlsx", fileFullPath);

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人，登录名重复"), url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        /// <summary>
        /// 获取文件保存路径
        /// </summary>
        private string GetPath()
        {
            var str = string.Empty;
            var virtualPath = "/UploadFile/Files/";
            var path = HttpContext.Current.Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fileFullPath = $"{path}{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            return fileFullPath;
        }

        /// <summary>
        /// 文件上传到blob
        /// </summary>
        private string SaveFile(string fileName, string fileFullPath)
        {
            //var fs = new FileStream(fileFullPath, FileMode.Open);
            var str = "#";
            //var bc = new BlobController();
            //var blobName = BlobHelper.GetBlobName(fileName);
            //var blobResult = bc.CreateBlod(blobName);
            //if (blobResult == ApiResultEunm.Success || blobResult == ApiResultEunm.Exist)
            //{
            //    //创建文件
            //    var apiResult = bc.UploadFileByStream(fs, fileName);
            //    if (apiResult.apiResultEunm == ApiResultEunm.Success && !string.IsNullOrEmpty(apiResult.info))
            //    {
            //        str = apiResult.info;
            //    }
            //}
            //fs.Dispose();
            //File.Delete(fileFullPath);
            return str;
        }
    }
}